<template>
    <div class="department-container">
      <a-card>
        <!-- 顶部操作区 -->
        <div class="table-operations">
          <!-- 添加搜索框 -->
          <a-row :gutter="16">
            <a-col :span="6">
              <a-input-search
                v-model:value="search"
                placeholder="请输入管理员名称"
                @search="fetchAdminList"
                enter-button
              />
            </a-col>
            <a-col :span="18" style="text-align: right">
              <a-button type="primary" @click="showAddModal">
                <plus-outlined />
                添加管理员
              </a-button>
            </a-col>
          </a-row>
        </div>
  

        <a-table
          :columns="columns"
          :data-source="adminList"
          :loading="loading"
          :pagination="pagination"
          @change="handleTableChange"
        >
          <!-- 操作列 -->
          <template  v-slot:bodyCell="{column,record}">
            <template v-if="column.dataIndex == 'action'">
            <a-space>
              <a-button type="link" @click="showEditModal(record)">编辑</a-button>
              <a-popconfirm
                title="确定要删除这个部门吗？"
                @confirm="handleDelete(record.adminId)"
              >
                <a-button type="link" danger>删除</a-button>
              </a-popconfirm>
            </a-space>
            </template>
          </template>
        </a-table>
  

        <a-modal
          :title="modalTitle"
          :open="modalVisible"
          @ok="handleModalOk"
          @cancel="handleModalCancel"
        >
          <a-form
            ref="formRef"
            :model="formData"
            :rules="rules"
            :label-col="{ span: 6 }"
            :wrapper-col="{ span: 16 }"
          >
            <a-form-item label="账号" name="loginName">
              <a-input v-model:value="formData.loginName" placeholder="请输入账号" />
            </a-form-item>
            <a-form-item label="密码" name="password">
              <a-input-password v-model:value="formData.password" placeholder="请输入密码" />
            </a-form-item>
          </a-form>
        </a-modal>
      </a-card>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted } from 'vue'
  import { message } from 'ant-design-vue'
  import { PlusOutlined } from '@ant-design/icons-vue'
  import { list,add,del,update } from '@/api/admin'
  // 表格列定义
  const columns = [
    {
      title: '账号',
      dataIndex: 'loginName',
      key: 'loginName',
    },
    {
      title: '密码',
      dataIndex: 'password',
      key: 'password',
      customRender: () => '******'
    },
    {
        title:'角色',
        dataIndex:'role',
        key:'role'
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
    },
  ]
  
  // 数据相关
  const loading = ref(false)
  const adminList = ref([])
  const pagination = ref({
    current: 1,
    pageSize: 10,
    total: 0,
  })
  const search=ref('')
  // 模态框相关
  const modalVisible = ref(false)
  const modalTitle = ref('添加管理员')
  const formRef = ref(null)
  const formData = ref({
    loginName: '',
    password: '',
    role:''
  })
  
  // 表单验证规则
  const rules = {
    loginName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
    ],
    password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ]
    
  }
  
  // 获取部门列表
  const fetchAdminList = async () => {
    loading.value = true
    try {

       const res = await list({
          pageNum:pagination.value.current,
          pageSize:pagination.value.pageSize,
          search:search.value
       })
       adminList.value = res.data.records
       pagination.value.total = res.data.total
    } catch (error) {
      message.error('获取管理员列表失败')
    } finally {
      loading.value = false
    }
  }
  
  // 表格分页变化
  const handleTableChange = (pag) => {
    pagination.value.current = pag.current
    pagination.value.pageSize = pag.pageSize
    fetchAdminList()
  }
  
  // 显示添加模态框
  const showAddModal = () => {
    modalTitle.value = '添加管理员'
    formData.value = {
      loginName: '',
      password: '',
      role:''
    }
    modalVisible.value = true
  }
  
  // 显示编辑模态框
  const showEditModal = (record) => {
    modalTitle.value = '编辑管理员'
    formData.value = { ...record }
    modalVisible.value = true
  }
  
  // 处理模态框确认
  const handleModalOk = () => {
    formRef.value?.validate().then(async () => {
      try {

        const res=formData.value.adminId ? await update(formData.value) : await add(formData.value)
        if(res.code===200){
            message.success(`${modalTitle.value}成功`)
            modalVisible.value = false
            fetchAdminList()
        }
      } catch (error) {
        message.error(`${modalTitle.value}失败`)
      }
    })
  }
  
  // 处理模态框取消
  const handleModalCancel = () => {
    modalVisible.value = false
    formRef.value?.resetFields()
  }
  
  // 处理删除部门
  const handleDelete = async (adminId) => {
    try {

       const res=await del(adminId)
       if(res.code===200){
        message.success('删除成功')
        fetchAdminList()
       }
   
    } catch (error) {
      message.error('删除失败')
    }
  }
  
  // 搜索处理函数
  const onSearch = () => {
    pagination.value.current = 1 // 重置页码到第一页
    fetchAdminList()
  }
  
  // 页面加载时获取管理员列表
  onMounted(() => {
    fetchAdminList()
  })
  </script>
  
  <style scoped>
  .department-container {
    padding: 24px;
  }
  
  .table-operations {
    margin-bottom: 16px;
    .ant-row {
      width: 100%;
    }
  }
  </style>